const category = require('../model/categoryModel.js');




//添加一个商品分类
async function add(ctx) {
    let data = {
        name: ctx.request.body.name,
        parent_id: ctx.request.body.parent_id,
        imgurl:ctx.request.body.imgurl
    }
    let result = await category.add(data)
    ctx.body = result
}

// 查询分类列表
async function list(ctx) {
    let page = ctx.request.query.page || 1;
    let num = ctx.request.query.num || 10;
    let parent_id = ctx.request.query.parent_id;
    let result = await category.list(page, num, {  parent_id })
    if (result.total) {
        ctx.body = { code: 1, msg: '', data: result }
    } else {
        ctx.body = { code: 0, mag: '暂无数据', data: '' }
    }
}

async function list1(ctx) {
    let cid  = ctx.request.query.zid;
    let result = await category.list1({cid })
    if (result) {
        ctx.body = { code: 1, msg: '', data: result }
    } else {
        ctx.body = { code: 0, mag: '暂无数据', data: '' }
    }
}




async function query(ctx) {
    let page = ctx.request.query.page || 1;
    let num = ctx.request.query.num || 10;
    let name = ctx.request.query.name;

    let result = await category.query(page, num, { name })
    if (result.total) {
        ctx.body = { code: 1, msg: '', data: result }
    } else {
        ctx.body = { code: 0, mag: '暂无数据', data: '' }
    }
}
// 修改分类
async function mod(ctx) {
    let name = ctx.request.body.name
    let imgurl = ctx.request.body.imgurl
    let id = ctx.params.id
 
    if (name) {
        let res = await category.mod({ name, id })
        if (res.code) {
            // ctx.body = res;
            ctx.body = res
        } else {
            ctx.body = res
        }
    }
    if (imgurl) {
        let res = await category.mod1({ imgurl, id })
        if (res.code) {
            ctx.body = res;
        } else {
            ctx.body = res
        }
    }
    
}

async function del(ctx) {
    let data = {
        id: ctx.params.id,
    }
    let res = await category.del(data)
    if (res.code) {
        ctx.body = res
    } else {
        ctx.body = res
    } 

}
  






module.exports = { add, list, mod,del, query ,list1}